/**
 * Created by spatra on 14-9-8.
 */

define(['app/physicsengine', 'app/entity', 'app/render', 'app/list'], function(PhysicsEngine, Entity, Render, List){
	function buildEntities(num){
		var entities = [];
		var conf = entitiesConfig;
		for(var i = 0; i < num; ++i ){
			var tmp = new Entity();
			tmp.setRandomStatus(conf.maxVel, conf.maxRadius,
				conf.containerWidth, conf.containerHeight);
			tmp.radius = entitiesConfig.maxRadius;
			entities.push(tmp);
		}

		return new List(entities);
	}

	var physicsEngineConfig = {
		canvasWidth: 1000,
		canvasHeight: 600,
		gridSize: 40,
		friction: 0.8,
		gravity: 0
	};

	var renderConfig = {
		drawType: 'simple',
		imgSrc: null
	};

	var entitiesConfig = {
		maxVel: 8,
		maxRadius: 12,
		containerWidth: 1000,
		containerHeight: 700
	};

	var FPS = 1000 / 40;

	var theEngine = null;
	var entities = null;
	var theRender = null;

	var runner = null;

	var theMousemove = null;

	var start = function(quantity, theCanvas, mousemove){
		var conf = physicsEngineConfig;
		if( theCanvas ){
			conf.canvasWidth = theCanvas.width;
			conf.canvasHeight = theCanvas.height;
		}

		theEngine = new PhysicsEngine(conf.canvasWidth, conf.canvasHeight,
			conf.gridSize, conf.friction, conf.gravity);


		if( theCanvas ){
			entitiesConfig.containerWidth = theCanvas.width;
			entitiesConfig.containerHeight = theCanvas.height;
		}
		entities =  buildEntities(quantity);

		theEngine.init(entities);

		theRender = new Render(theCanvas, renderConfig.drawType, renderConfig.imgSrc);

		theMousemove = mousemove;

		runner = setInterval(mainLoop, FPS);
	};

	var mainLoop = function(){
		theRender.draw(entities);
		theEngine.run(entities);
		theMousemove.run(entities);
	};

	var pause = function(){
		clearInterval(runner);
	};

	var recover = function(){
		runner = setInterval(mainLoop, FPS);
	};

	var addEntities = function(addNum){
		var add = buildEntities(addNum);
		entities.merge(add);
	};


	return {
		start: start,
		setInitConf: function(aConfig){
			if( aConfig.physicsengine ){
				physicsEngineConfig = aConfig.physicsengine;
			}
		},
		pause: pause,
		recover: recover,
		addEntities: addEntities
	};
});